<!--
 * @页面名称:定时任务
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="timingTask card">
    <el-space style="margin-bottom: 10px">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button @click="refresh">刷新</el-button>

      <el-dropdown>
        <el-button>
          更多
          <el-icon class="el-icon--right"> <arrow-down /> </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="nowStart">立即执行</el-dropdown-item>
            <el-dropdown-item @click="edit">编辑</el-dropdown-item>
            <el-dropdown-item @click="getLog">日志</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-space>
    <div style="height: calc(100% - 42px)">
      <stable :columns="tableSetting.columns" :data="tableSetting.data" @rowClick="rowClick"></stable>
    </div>
    <modal v-model:visible="modalSetting.visible" :title="modalSetting.title" width="600" @ok="ok">
      <el-form label-width="120" :model="taskFormData" :rules="rules" ref="taskForm">
        <el-form-item label="任务名称：" prop="Name">
          <el-input v-model="taskFormData.Name"></el-input>
        </el-form-item>
        <el-form-item label="任务分组：" prop="JobGroup">
          <el-input v-model="taskFormData.JobGroup"></el-input>
        </el-form-item>
        <el-form-item label="程序集名称：" prop="AssemblyName">
          <el-input v-model="taskFormData.AssemblyName"></el-input>
        </el-form-item>
        <el-form-item label="任务类名：" prop="ClassName">
          <el-input v-model="taskFormData.ClassName"></el-input>
        </el-form-item>
        <el-form-item label="启用url：">
          <el-checkbox v-model="taskFormData.IsStart"></el-checkbox>
        </el-form-item>
        <el-form-item v-if="taskFormData.IsStart" label="请求url">
          <el-input v-model="taskFormData.RequestUrl" />
        </el-form-item>
        <el-form-item v-if="taskFormData.IsStart" label="请求类型">
          <el-select v-model="taskFormData.RequestType">
            <el-option label="None" :value="0"></el-option>
            <el-option label="Get" :value="1"></el-option>
            <el-option label="Post" :value="2"></el-option>
            <el-option label="Put" :value="4"></el-option>
            <el-option label="Delete" :value="8"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="taskFormData.IsStart" label="请求头">
          <el-tooltip effect="dark" placement="bottom">
            <template #content>
              <span>格式: {"key":"value","key2":"value2"}</span>
            </template>
            <el-input v-model="taskFormData.RequestHeader" placeholder="请输入Headers信息,如Cookies,授权认证等" />
          </el-tooltip>
        </el-form-item>
        <el-form-item v-if="taskFormData.IsStart" label="请求参数">
          <el-tooltip effect="dark" placement="bottom">
            <template #content>
              <span>格式: {"key":"value","key2":"value2"}</span>
            </template>
            <el-input v-model="taskFormData.RequestParams" placeholder="请输入请求参数(json字符串)" />
          </el-tooltip>
        </el-form-item>
        <el-form-item label="触发器类型：">
          <el-select v-model="taskFormData.TriggerType">
            <el-option label="Simple/(普通)" :value="0"></el-option>
            <el-option label="Cron/(表达式)" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="taskFormData.TriggerType === 1" label="运行时间表达式">
          <el-select v-model="taskFormData.Cron" placeholder="请选择Cron表达式">
            <el-option label="0 */1 * * * ?" value="0 */1 * * * ?"></el-option>
            <el-option label="1 0 0 * * ?" value="1 0 0 *  *  ?"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期：" prop="BeginTime">
          <el-date-picker v-model="taskFormData.BeginTime" style="width: 100%" type="date" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="结束日期：" prop="EndTime">
          <el-date-picker v-model="taskFormData.EndTime" style="width: 100%" type="date" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="执行间隔(秒)：" v-if="taskFormData.TriggerType === 0">
          <el-input type="number" v-model="taskFormData.IntervalSecond"></el-input>
        </el-form-item>
      </el-form>
    </modal>
  </div>
</template>

<script setup lang="tsx" name="timingTask">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import useCurrentInstance from "@/utils/useCurrentInstance";

const { proxy } = useCurrentInstance();
// 表格配置
const tableSetting = reactive({
  // 表头
  columns: [
    {
      title: "序号",
      width: 100,
      sortable: true,
      slots: {
        default: ({ rowIndex }) => {
          return [
            <div class="vxe-order">
              <span class="order-circle">{rowIndex || 0}</span>
            </div>
          ];
        }
      }
    },
    { title: "任务名称", field: "Name", sortable: true },
    { title: "任务分组", field: "JobGroup", sortable: true },
    { title: "上次执行时间", field: "PreviousFireTime", sortable: true },
    { title: "下次执行时间", field: "NextFireTime", sortable: true },
    {
      title: "触发器类型",
      field: "TriggerType",
      sortable: true,
      slots: {
        default: ({ row }) => {
          return [<span>{row.TriggerType === 0 ? "Simple/(普通)" : "Cron/(表达式)"}</span>];
        }
      }
    },
    { title: "执行次数", field: "RunTimes", sortable: true },
    { title: "运行时间表达式", field: "Cron", sortable: true },
    { title: "执行状态", field: "DisplayState", sortable: true },
    {
      title: "操作",
      slots: {
        default: ({ row }) => {
          return [
            <el-space>
              <el-button size="small" onClick={() => onEnable(row)}>
                {row.TriggerState === "Normal" ? "暂停" : "恢复"}
              </el-button>
              <el-button size="small" type="danger" onClick={() => del(row)}>
                删除
              </el-button>
            </el-space>
          ];
        }
      }
    }
  ],
  // 数据集合
  data: [],
  // 单击保存对象
  rowClickObj: {} as any
});
// 弹出框配置
const modalSetting = reactive({
  visible: false,
  title: ""
});
// 表单绑定字段
const taskFormData = ref({
  Name: "",
  JobGroup: "",
  AssemblyName: "Master.Tasks",
  ClassName: "HttpJob",
  IsStart: false,
  JobParams: "",
  RequestUrl: "",
  RequestType: 0,
  RequestHeader: "",
  RequestParams: "",
  TriggerType: 0,
  Cron: "",
  BeginTime: "",
  EndTime: "",
  IntervalSecond: 0
});
// 表单实例
const taskForm = ref<FormInstance>();
// 表单规则
const rules = reactive<FormRules>({
  Name: [{ required: true, message: "请填写名称!", trigger: "blur" }],
  JobGroup: [{ required: true, message: "请填写任务分组!", trigger: "blur" }],
  AssemblyName: [{ required: true, message: "请填写程序集名称!", trigger: "blur" }],
  ClassName: [{ required: true, message: "请填写任务类名!", trigger: "blur" }],
  BeginTime: [{ required: true, message: "请填写开始时间!", trigger: "change" }],
  EndTime: [{ required: true, message: "请填写结束时间!", trigger: "change" }]
});
// 获取表格数据
const getTableData = () => {
  proxy.$vueAxios.get("MasterBaseTasks").then((res: any) => {
    tableSetting.data = res.List;
  });
};
// 新增事件
const add = () => {
  modalSetting.visible = true;
  modalSetting.title = "新增";
  taskForm.value?.resetFields();
};
// 刷新事件
const refresh = () => {
  getTableData();
};
// 表格单击
const rowClick = ({ row }: any) => {
  tableSetting.rowClickObj = row;
};
// 恢复事件
const onEnable = (row: any) => {
  proxy.$vueAxios.get("MasterBaseTasks/Resume", { id: row.ID }).then((res: any) => {
    if (res.Mark) {
      getTableData();
    }
  });
};
// 删除
const del = (row: any) => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.get("MasterBaseTasks/Delete", { id: row.ID }).then((res: any) => {
        if (res.Mark) {
          getTableData();
          proxy.$message.success("删除成功");
        } else {
          proxy.$message.error("删除失败");
        }
      });
    });
};
// 立即执行
const nowStart = () => {
  proxy.$vueAxios.get("MasterBaseTasks/NowTriggerJob", { id: row.ID }).then((res: any) => {
    if (res.Mark) {
      getTableData();
    }
  });
};
// 编辑
const edit = () => {
  modalSetting.visible = true;
  modalSetting.title = "编辑";
  taskFormData.value.Name = tableSetting.rowClickObj.Name;
  taskFormData.value.JobGroup = tableSetting.rowClickObj.JobGroup;
  taskFormData.value.AssemblyName = tableSetting.rowClickObj.AssemblyName;
  taskFormData.value.ClassName = tableSetting.rowClickObj.ClassName;
  taskFormData.value.IsStart = tableSetting.rowClickObj.IsStart;
  taskFormData.value.JobParams = tableSetting.rowClickObj.JobParams;
  taskFormData.value.RequestUrl = tableSetting.rowClickObj.RequestUrl;
  taskFormData.value.RequestType = tableSetting.rowClickObj.RequestType;
  taskFormData.value.RequestHeader = tableSetting.rowClickObj.RequestHeader;
  taskFormData.value.RequestParams = tableSetting.rowClickObj.RequestParams;
  taskFormData.value.TriggerType = tableSetting.rowClickObj.TriggerType;
  taskFormData.value.Cron = tableSetting.rowClickObj.Cron;
  taskFormData.value.BeginTime = tableSetting.rowClickObj.BeginTime;
  taskFormData.value.EndTime = tableSetting.rowClickObj.EndTime;
  taskFormData.value.IntervalSecond = tableSetting.rowClickObj.IntervalSecond;
};
// 日志
const getLog = () => {
  proxy.$vueAxios.get("MasterBaseTasks/GetJobLogs", { id: tableSetting.rowClickObj.ID }).then((res: any) => {
    console.log(res);
  });
};
// 弹出框确认事件
const ok = () => {
  taskForm.value?.validate(valid => {
    if (valid) {
      if (modalSetting.title === "新增") {
        const params = {
          id: proxy.$global.createID(),
          name: taskFormData.value.Name,
          jobGroup: taskFormData.value.JobGroup,
          cron: taskFormData.value.Cron,
          assemblyName: taskFormData.value.AssemblyName,
          className: taskFormData.value.ClassName,
          requestUrl: taskFormData.value.RequestUrl,
          requestType: taskFormData.value.RequestType,
          requestHeader: taskFormData.value.RequestHeader,
          requestParams: taskFormData.value.RequestParams,
          beginTime: taskFormData.value.BeginTime,
          endTime: taskFormData.value.EndTime,
          triggerType: taskFormData.value.TriggerType,
          intervalSecond: taskFormData.value.IntervalSecond,
          isStart: taskFormData.value.IsStart,
          jobParams: taskFormData.value.JobParams
        };
        proxy.$vueAxios.post("MasterBaseTasks", params).then((res: any) => {
          if (res.Mark) {
            modalSetting.visible = false;
            getTableData();
            proxy.$message.success("添加成功!");
          }
        });
      } else if (modalSetting.title === "编辑") {
        const params = {
          id: tableSetting.rowClickObj.ID,
          name: taskFormData.value.Name,
          jobGroup: taskFormData.value.JobGroup,
          cron: taskFormData.value.Cron,
          assemblyName: taskFormData.value.AssemblyName,
          className: taskFormData.value.ClassName,
          requestUrl: taskFormData.value.RequestUrl,
          requestType: taskFormData.value.RequestType,
          requestHeader: taskFormData.value.RequestHeader,
          requestParams: taskFormData.value.RequestParams,
          beginTime: taskFormData.value.BeginTime,
          endTime: taskFormData.value.EndTime,
          triggerType: taskFormData.value.TriggerType,
          intervalSecond: taskFormData.value.IntervalSecond,
          isStart: taskFormData.value.IsStart,
          jobParams: taskFormData.value.JobParams
        };
        proxy.$vueAxios.post("MasterBaseTasks/Update", params).then((res: any) => {
          if (res.Mark) {
            modalSetting.visible = false;
            getTableData();
            proxy.$message.success("修改成功!");
          }
        });
      }
    }
  });
};

onMounted(() => {
  getTableData();
});
</script>
<style lang="scss" scoped>
.timingTask {
  height: 100%;
}
</style>
